<script setup lang="ts">
import Driver from "driver.js";
import steps from "./step";
import "driver.js/dist/driver.min.css";
import tagIcon from "@/assets/icons/tag.png";
import typeIcon from "@/assets/icons/type.png";
import noticeIcon from "@/assets/icons/notice.png";
import code from "@/assets/images/footer-code.jpg";
import ThingCardSkeleton from "@/components/ThingCardSkeleton/index.vue";
import TypeCard from './components/type-card/index.vue'
import { getNotice } from '@/api/notice/index'
import {
  reactive,
  defineAsyncComponent,
  watch,
  onMounted,
  computed,
} from "vue";
import { useThingStore } from "@/store/modules/thing";
import { statusColor } from "@/enums/thingEnum";
import { storage } from "@/utils/lib/Storage";
import { FIRST_LOGIN_TIME } from "@/store/mutation-types";
import { deepClone } from "@/utils/lib/clone";
import { getAllThing, getThingStatus, getThingType } from "@/api/thing";
const ThingCard = defineAsyncComponent(
  () => import("@/components/ThingCard/index.vue")
);
const thingStore = useThingStore();
const key = computed<string>(() => thingStore.key)


const pageData = reactive<Record<string, any>>({
  tags: [],                // 标签
  type: [],                 // 类别
  init: false as boolean,  //数据初始化
  thingList: [],        // 启事列表
  isMore: true as boolean,         // 是否展示加载更多
  loading: false as boolean,       // 加载动画显示
  thingCount: 0 as number,         // 启事总数
  pageSize: 3 as number,
  pageNo: 1 as number,
  statusId: 0 as number,
  typeId: 0 as number,
  key: '' as string,
  driver: null,
  noticeTime: '' as string,
  noticeInfo: '' as string,
  pageEnterTime:0 as number     // 进入页面初始化时间
});
pageData.pageEnterTime = new Date().getTime()
onMounted(() => {
  pageData.driver = new Driver({
    opacity: 0.75,
    animate: true,
    doneBtnText: "我知道了",
    allowClose: false,
    closeBtnText: "跳过", //  关闭按钮文案
    nextBtnText: "下一步", // 下一步的按钮文案
    prevBtnText: "上一步", // 上一步的按钮文案
    keyboardControl: true, // 允许通过键盘控制（退出关闭，箭头键移动）
    // onNext: (Element) => { }, // 任何步骤中移到到下一步时调用Called when moving to next step on any step
    // onPrevious: (Element) => { }, // 任何步骤中移到到上一步时调用Called when moving to next step on any step
  });
});

watch(() => key.value, (val) => {
  pageData.key = key.value
  searchThing(val)

})

/**
 * 根据关键字搜索
 */
const searchThing = async (key: any) => {
  try {
    pageData.pageNo = 1
    pageData.statusId = 0
    pageData.typeId = 0
    pageData.thingList = []
    pageData.key = key
   
    await getThingList()


  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 获取启事状态
 */
const getStatus = async () => {
  try {

    const res = await getThingStatus();
    if (res.data.code === 200) {
      pageData.tags = res.data.data
      console.log(pageData.tags);

    }
    return Promise.resolve(res);
  } catch (error) {
    return Promise.reject(error);
  }
};

// 判断是否首次登录
const isFirstLogin = () => {
  const firstLoginTime = storage.get(FIRST_LOGIN_TIME, "");
  const curTime = new Date().getTime();
  const ex = 60 * 60 * 24 * 365;
  if (firstLoginTime === "") {
    storage.set(FIRST_LOGIN_TIME, JSON.stringify(curTime), ex);
    pageData.driver.defineSteps(steps);
    pageData.driver.start();
  }
};

/**
 * 获取首页启事列表
 */
const getThingList = async () => {

  try {
    pageData.loading = true
    let data = {
      pageSize: pageData.pageSize,
      pageNo: pageData.pageNo,
      statusId: pageData.statusId,
      typeId: pageData.typeId,
      key:pageData.key,
      time:pageData.pageEnterTime
    }

    console.log(data);

    const res = await getAllThing(data)
    if (res.data.code === 200) {

      pageData.thingList = pageData.thingList.concat(res.data.data.data)
      pageData.thingCount = res.data.data.dataLength
      pageData.loading = false
      return Promise.resolve(res)
    }
  } catch (error) {
    return Promise.reject(error)
  }
}

const init = async () => {
  try {
    await getThingList()
    await getStatus();
    await getType()
    await getNoticeInfo()
    isFirstLogin();
    pageData.init = true;
    pageData.isMore = true;
  } catch (error) {
    return Promise.reject(error);
  }
};

/**
 * 根据标签获取启事
 * @param tag 标签
 */
const showThingByTag = async (statusId: number) => {
  try {
    pageData.pageNo = 1
   
    pageData.statusId = statusId
    pageData.typeId = 0
    pageData.key = ''
    pageData.thingList = []
   
    await getThingList()


  } catch (error) {
    return Promise.reject(error)
  }
};

/**
 * 根据类型id获取启事列表
 * @param typeId 类型id
 */
const showThingByType = async (typeId: number) => {
  try {
    pageData.pageNo = 1
    pageData.thingList = []
    pageData.typeId= typeId
    pageData.statusId = 0
    pageData.key = ''
  
    await getThingList()
  } catch (error) {
    return Promise.reject(error)
  }
};


/**
 * 获取更多启事
 */
const getMoreThing = async () => {
  try {

    
    pageData.pageNo += 1
    await getThingList()
    
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 获取启事类别
 */
const getType = async () => {
  try {
    const res = await getThingType()
    if (res.data.code === 200) {
      pageData.type = res.data.data
    }
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 获取公告信息
 */
const getNoticeInfo = async () => {
  try {
    const res = await getNotice({
      pageNo: 1,
      pageSize: 5
    })
    if (res.data.code === 200) {
      let allData = deepClone(res.data.data.result)
      allData.sort(
        (a, b) => new Date(b.create_time).getTime() - new Date(a.create_time).getTime()
      );
      pageData.noticeTime = allData[0].create_time
      pageData.noticeInfo = allData[0].content
    }
  } catch (error) {
    return Promise.reject(error)
  }
}

init();
</script>

<template>
  <div class="index">
    <div class="things-box">
      <div class="title-box">
        <p class="title">启事</p>
        <p>
          共<span class="count">{{ pageData.thingCount }}</span>篇
        </p>
      </div>
      <div class="content">
        <!-- <p class="without">暂无启事...</p> -->
        <!-- <ThingCardSkeleton :thingList="pageData.thingList"/> -->
        <!-- <ThingCard :thingList="pageData.thingList" /> -->

        <!-- <ThingCard
              					:thingInfo="item"
              					v-for="item in pageData.thingList"
              					:key="item.id"
              				/> -->

        <Suspense>
          <template #default>


            <div v-if="!(pageData.thingList.length === 0 && pageData.thingCount !== 0)">
              <ThingCard
                :thingList="pageData.thingList.sort((a, b) => new Date(b.TIME).getTime() - new Date(a.TIME).getTime())" />
              <div class="load-more" @click="getMoreThing" v-if="pageData.thingList.length < pageData.thingCount">
                <p v-if="!pageData.loading">加载更多</p>
                <div v-else class="loading">
                  <div class="circle-1"></div>
                  <div class="circle-2"></div>
                </div>
              </div>
              <div v-else class="no-load">
                <p>已展示全部启事了</p>
              </div>
            </div>
            <div v-else>
              <ThingCardSkeleton /> 
            </div>
            <!-- <p v-else class="without-thing">暂无启事</p> -->

          </template>

          <template #fallback>
            <div>
              <ThingCardSkeleton />
            </div>
          </template>
        </Suspense>
      </div>
    </div>
    <!-- <div class="pagination-box">
              			<n-pagination v-model:page="page" :page-count="100" />
              		</div> -->
    <TypeCard class="tag" :icon="tagIcon" :title="'标签'" id="tag-steps">
      <div class="tags-box">
        <n-tag :type="statusColor[item.STATUS]" v-for="item in   pageData.tags" :key="item.id" class="item-tag"
          @click="showThingByTag(item.id)">
          <span class="name">{{ item.STATUS }}</span><span>{{ item.status_count }}</span>
        </n-tag>
      </div>
    </TypeCard>
    <TypeCard class="type" :icon="typeIcon" :title="'分类'" id="type-steps">
      <div class="types-box">
        <n-tag type="info" v-for="item in pageData.type" :key="item.id" class="item-type"
          @click="showThingByType(item.id)">
          <span class="name">{{ item.TYPE }}</span><span>{{ item.type_count }}</span>
        </n-tag>
      </div>
    </TypeCard>
    <TypeCard class="notice" :icon="noticeIcon" :title="'公告'">
      <div class="notice-box">
        <p class="content">{{ pageData.noticeInfo }}</p>
        <p class="time">{{ pageData.noticeTime }}</p>
      </div>
    </TypeCard>
    <div class="code">
      <p class="title">扫码联系我们</p>
      <div class="line"></div>
      <div class="img">
        <n-image-group>
          <n-image width="160" height="160" :src="code" lazy>
            <template #placeholder>
              <Loading />
            </template>
          </n-image>
        </n-image-group>
      </div>
    </div>
    <div class="empty"></div>
  </div>
</template>

<style lang="less" scoped>
@import "@/styles/mixin.less";

.index {
  display: grid;
  grid-template-columns: auto 318px;
  grid-template-rows: 150px 150px 150px 140px auto;
  gap: 30px 50px;
  grid-template-areas:
    "things tag"
    "things type"
    "things notice"
    "things code"
    "things empty";

  .things-box {
    grid-area: things;

    border: 2px solid #ccc;
    box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);

    // .without-thing {
    //   padding-top: 10px;
    //   .flex(row, center, center);

    //   .title {
    //     font-size: 20px;
    //   }
    // }

    .title-box {
      height: 50px;
      padding: 0 20px;
      .flex(row, space-between, center);
      border-bottom: 2px solid #ccc;

      .title {
        color: rgb(3, 180, 170);
        font-weight: bold;
        font-size: 20px;
      }

      .count {
        font-size: 22px;
        color: orange;
        margin: 0 2px;
      }
    }

    .content {
      .flex(column, flex-start, center);
      // border: 1px solid #aaa;
      padding: 10px 30px;

      // .without-thing {
      //   font-size: 18px;
      // }

      .load-more {
        // border: 1px solid #ccc;
        margin: 10px 0;
        height: 40px;
        background-color: rgb(252, 252, 252);
        font-size: 17px;
        // width: 800px;
        .flex(row, center, center);

        &:hover {
          background-color: rgb(245, 246, 248);
          cursor: pointer;
        }

        .loading {
          .flex(row, center, center);

          .circle-1 {
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background-color: blue;
            margin-right: 5px;
            animation: circle1 .6s linear infinite;
          }

          .circle-2 {
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background-color: red;
            animation: circle2 .6s linear infinite;
          }
        }

        @keyframes circle1 {
          50% {
            transform: translateX(20px);
          }
        }

        @keyframes circle2 {
          50% {
            transform: translateX(-20px);
          }
        }
      }

      .no-load {
        margin: 10px 0;
        height: 40px;
        color: #666;
        // width: 800px;
        .flex(row, center, center);
      }

      .without-thing {
        margin-top: 20px;
        text-align: center;
        font-size: 20px;
        color: cornflowerblue;
      }
    }
  }

  .pagination-box {
    // margin-top: 30px;
    grid-area: pagination;
    width: 800px;
    .flex(row, center, center);
  }

  .tag {
    grid-area: tag;

    .tags-box {
      height: 100px;
      display: grid;
      grid-template-columns: repeat(2, auto);
      grid-template-rows: repeat(2, auto);
      place-items: center center;

      .item-tag {
        cursor: pointer;

        .name {
          margin-right: 5px;
        }
      }
    }
  }

  .type {
    grid-area: type;

    .types-box {
      // height: 100px;
      display: grid;
      grid-template-columns: auto auto auto auto;
      grid-template-rows: 50px 50px;
      gap: 0 10px;

      place-items: center center;

      .item-type {
        cursor: pointer;
        .flex(row, center, center);

        .name {
          margin-right: 5px;
        }
      }
    }
  }

  .notice {
    grid-area: notice;

    .notice-box {
      text-align: center;
      padding-top: 20px;
      // padding: 20px;
      // border: 1px solid #ccc;
      height: 100px;

      // width: 80%;
      // .flex(column,center,center);
      .content {
        margin-bottom: 10px;
      }
    }
  }

  .code {
    grid-area: code;
    position: relative;

    .title {
      font-weight: bold;
      font-size: 20px;
      width: 150px;
      // border: 1px solid #ccc;
      background-color: #fff;
      text-align: center;
      position: absolute;
      top: -15px;
      left: 85px;
    }

    .line {
      width: 318px;
      height: 1px;
      background-color: #ccc;
    }

    .img {
      margin-top: 20px;
      // border: 1px solid #ccc;

      width: 318px;

      .flex(row, center, center);
    }
  }

  .empty {
    grid-area: empty;
  }
}
</style>
